package com.whitehatsec.sentineldataexchange;

import com.whitehatsec.sentineldataexchange.model.WhiteHatSite;
import java.util.*;

import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Handler class for the SAXParser XML parser.
 * Provides methods to populate a list of WhiteHat Sites
 *
 * @author August Detlefsen [augustd@codemagi.com]
 * Copyright 2010 WhiteHat Security
 */
public class WhiteHatSiteListLoader extends DefaultHandler {

	private WhiteHatSite tempSite = null;
	private HashMap<String, WhiteHatSite> loadedSites = new HashMap<String, WhiteHatSite>();
	private String tempVal = null;

	private void clearPrivateData() {
		this.tempSite = null;
	}

	// called by the SAXParser at the beginning of every XML element
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		this.tempVal = "";

		if (qName.equalsIgnoreCase("site")) {
			this.tempSite = new WhiteHatSite();
			this.tempSite.setSiteID(attributes.getValue("id"));
		}
	}

	// called by the SAXParser at every chunk of character data
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		this.tempVal = this.tempVal + new String(ch, start, length);
	}

	// called by the SAXParser at the end of every XML element
	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (qName.equalsIgnoreCase("site")) {
			// end of site tab
			// add the site to the list
			this.loadedSites.put(this.tempSite.getSiteID(), this.tempSite);

			System.out.println("Site ID: " + this.tempSite.getSiteID());
			System.out.println("  Label: " + this.tempSite.getSiteLabel());
			this.clearPrivateData();

		} else if (qName.equalsIgnoreCase("label")) {
			this.tempSite.setSiteLabel(this.tempVal);
		}
	}  // endElement

	public HashMap<String, WhiteHatSite> getSites() {
		return this.loadedSites;
	}
}
